import "dart:io";
import "package:file_transfer/model/simple_model.dart";
import "package:file_transfer/widget/app_bar_widget.dart";
import "package:flutter/material.dart";
import "package:open_file/open_file.dart";
import "package:provider/provider.dart";
import "package:path/path.dart";

class FilePage extends StatefulWidget {
  const FilePage({super.key});

  @override
  State<FilePage> createState() => _FilePageState();
}

class _FilePageState extends State<FilePage> {
  List<String> _getFiles(BuildContext context){
    final simpleModel = context.read<SimpleModel>();
    final path = simpleModel.receiveDirectoryPath;
    final dir = Directory(path);
    if (dir.existsSync()) {
      return dir.listSync().whereType<File>().toList()
          .map((e) => basename(e.path))
          .toList();
    }
    return [];
  }

  _openFile(String fileName, BuildContext context) async {
    final simpleModel = context.read<SimpleModel>();
    final path = simpleModel.receiveDirectoryPath;
    await OpenFile.open("$path/$fileName");
  }

  _delFile(String name,BuildContext context)=> showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: const Text("确认操作"),
        content: Text("你确定要删除($name)吗？"),
        actions: [
          TextButton(
            child: const Text("取消"),
            onPressed: () {
              Navigator.of(context).pop(); // 关闭对话框
            },
          ),
          TextButton(
            child: const Text("确定"),
            onPressed: () {
              // 执行删除操作
              final simpleModel = context.read<SimpleModel>();
              final path = simpleModel.receiveDirectoryPath;
              final file = File("$path/$name");
              if(file.existsSync()){
                file.deleteSync();
                setState(() {});
              }
              Navigator.of(context).pop(); // 关闭对话框
            },
          ),
        ],
      );
    },
  );

  @override
  Widget build(BuildContext context) {
    final files = _getFiles(context);
    return Scaffold(
      appBar: pageAppBar("接收的文件", context),
      body: ListView.builder(
          itemCount: files.length,
          itemBuilder: (BuildContext context, int index) {
            return FileItem(files[index],openFile: _openFile,delFile: _delFile,);
          }),
    );
  }
}

typedef FileCallback = void Function(String,BuildContext);
class FileItem extends StatelessWidget {

  final String name;
  final FileCallback openFile;
  final FileCallback delFile;
  const FileItem(this.name,{super.key,required this.openFile,required this.delFile});


  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onLongPress: () => delFile(name,context),
      onTap:() => openFile(name,context),
      child: Container(
        padding: const EdgeInsets.all(10.0),
        margin: const EdgeInsets.all(10.0),
        decoration: BoxDecoration(
          color: Colors.blueAccent,
          borderRadius: BorderRadius.circular(15.0),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(name,style: const TextStyle(
              fontSize: 22,
              color: Colors.white
            ),)
          ],
        ),
      ),
    );
  }
}

